package com.asd.common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.plugin.activerecord.Record;

public class Render {
	public static void renderJson(ServletResponse resp, Object code, Object msg) {
		resp.setContentType("application/json;charset=utf-8");
		try (PrintWriter out = resp.getWriter()){
			JSONObject json = new JSONObject();
			json.put("code", code);
			json.put("msg", msg);
			json.put("data", new JSONObject());
			out.println(JSON.toJSONString(json));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void renderText(ServletResponse resp, Object msg) {
		resp.setContentType("text/html;charset=utf-8");
		try (PrintWriter out = resp.getWriter()){
			out.println(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void render(ServletResponse resp, Object msg) {
		if(checkIsBeanModel(msg)){
			resp.setContentType("application/json;charset=utf-8");
			try (PrintWriter out = resp.getWriter()){
				String json = JSON.toJSONString(msg, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty);
				out.println(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			resp.setContentType("text/html;charset=utf-8");
			try (PrintWriter out = resp.getWriter()){
				out.println(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


	}
	public static Record renderPage(int count, Object data) {
		Record r = new Record();
		r.set("count", count);
		r.set("data", data);
		r.set("code", 0);
		r.set("msg", "");
		return r;
	}

	/**
	 * 判断是不是bean
	 *
	 * @param obj
	 * @return
	 */
	public static boolean checkIsBeanModel(Object obj) {
		if (obj instanceof Integer) {
			return false;
		} else if (obj instanceof String) {
			return false;
		} else if (obj instanceof Double) {
			return false;
		} else if (obj instanceof Float) {
			return false;
		} else if (obj instanceof Long) {
			return false;
		} else if (obj instanceof Boolean) {
			return false;
		} else if (obj instanceof Date) {
			return false;
		} else if (obj instanceof Object[]) {
			return false;
		}else {
			return true;
		}
	}

}
